package com.hs;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: hs
 * @Description: 你好
 * @Date: Create in 19:55 2019/4/16
 */
public class LockTest {

    private int len = 0;
    ReentrantLock lock = new ReentrantLock(true);
    public static void main(String[] args) {

        LockTest test = new LockTest();
        ExecutorService executorService = new ThreadPoolExecutor(1, 10, 10, TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(40));
        try {
            for (int i = 0; i <40; i++) {
                executorService.execute(test.new myRunable());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }

    }

    private class myRunable implements Runnable {
        @Override
        public void run() {
            lockMethod();
        }
    }

    private void lockMethod() {

        lock.lock();
        int i = len;
        i = i+1;
        len = i;
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(len);
        System.out.println(Thread.currentThread().getName());
        lock.unlock();
    }
}
